{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# numpy",
   "id": "76dad6bfcdd1b087"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "import numpy as np",
   "id": "a88b12d1a9f7288d",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 生成numpy数组\n",
    "a = np.array([1, 2, 3])\n",
    "print(a)"
   ],
   "id": "787cdc462d8102f5",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# numpy算数运算\n",
    "#当x和y的元素个数相同时，可以对各个元素进行算术运算。如果元素个数不同，程序就会报错，所以元素个数保持一致非常重要\n",
    "b = np.array([4, 5, 6])\n",
    "print(a + b)  # 数组加法\n",
    "print(a * b)  # 数组乘法\n",
    "print(a - b)  # 数组减法\n",
    "print(a / b)  # 数组除法\n",
    "\n",
    "c = np.array([1, 2])\n",
    "# print(a + c)  # 报错，元素个数不一致"
   ],
   "id": "7b8d2a465af3a076",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# numpy广播机制\n",
    "# 当两个数组的形状不同时，NumPy会尝试通过广播机制来使它们的形状兼容，从而进行算术运算。如果两个数组的维度数不同，形状较小的数组\n",
    "num = 2\n",
    "print(a + num)  # 数组加法\n",
    "print(a * num)  # 数组乘法\n",
    "print(a - num)  # 数组减法\n",
    "print(a / num)  # 数组除法"
   ],
   "id": "9f0868e033284f7f",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 多维数组\n",
    "d = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "print(d)\n",
    "# 矩阵的形状\n",
    "print(d.shape)\n",
    "# 矩阵的数据类型\n",
    "print(d.dtype)"
   ],
   "id": "8af3d7db2662abba",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 同样的，多维数组也可以利用广播机制进行运算\n",
    "print(d * 10)\n",
    "\n",
    "# e = np.array([1, 2, 3,4])\n",
    "# print(d*e)"
   ],
   "id": "de5dbe26e4ea50ba",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "X = np.array([[51, 55], [14, 19], [0, 4]])\n",
    "# 转化为一维数组\n",
    "print(X.flatten())\n",
    "\n",
    "# 对NumPy数组使用不等号运算符等（上例中是X > 15），结果会得到一个布尔型的数组\n",
    "print(X > 10)\n",
    "# 筛选出符合条件的元素转化为一维数组\n",
    "print(X[X > 15])"
   ],
   "id": "f42d3b819e63c7a3",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
